<template>
  <a-modal
    v-model:visible="visible"
    :title="`设备登记记录 - ${deviceName || ''}`"
    :width="1000"
    :mask-closable="false"
    :esc-to-close="false"
    :footer="false"
    :closable="true"
  >
    <template #title>
      <div class="modal-title">
        <span>{{ `设备登记记录 - ${deviceName || ''}` }}</span>
        <a-button
          type="primary"
          :loading="exportLoading"
          @click="handleExport"
        >
          <template #icon><icon-download /></template>
          <template #default>导出Excel</template>
        </a-button>
      </div>
    </template>

    <a-table
      v-if="recordList.length > 0 || loading"
      :data="recordList"
      :loading="loading"
      :pagination="false"
      :scroll="{ x: '100%', y: '60vh' }"
      :bordered="true"
      row-key="id"
    >
      <template #columns>
        <a-table-column title="序号" :width="60">
          <template #cell="{ rowIndex }">
            {{ rowIndex + 1 }}
          </template>
        </a-table-column>
        <a-table-column title="设备名称" data-index="deviceName" :width="120" />
        <a-table-column title="登记时间" data-index="registerDate" :width="160">
          <template #cell="{ record }">
            {{ formatDateTime(record.registerDate) }}
          </template>
        </a-table-column>
        <a-table-column title="使用人" data-index="userName" :width="100">
          <template #cell="{ record }">
            {{ record.userName || '-' }}
          </template>
        </a-table-column>
        <a-table-column title="使用位置" data-index="locationName" :width="120">
          <template #cell="{ record }">
            {{ record.locationName || '-' }}
          </template>
        </a-table-column>
        <a-table-column title="操作人" data-index="operatorName" :width="100">
          <template #cell="{ record }">
            {{ record.operatorName || '-' }}
          </template>
        </a-table-column>
        <a-table-column title="创建时间" data-index="createTime" :width="160">
          <template #cell="{ record }">
            {{ formatDateTime(record.createTime) }}
          </template>
        </a-table-column>
      </template>
    </a-table>

    <a-empty v-else description="暂无登记记录" />
  </a-modal>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { Message } from '@arco-design/web-vue'
import dayjs from 'dayjs'
import { 
  type DeviceRegisterRecordResp,
  listDeviceRegisterRecords,
  exportDeviceRegisterRecords
} from '@/apis/generator/deviceCirculation'
import { useDownload } from '@/hooks'

const visible = ref(false)
const loading = ref(false)
const exportLoading = ref(false)
const recordList = ref<DeviceRegisterRecordResp[]>([])
const circulationId = ref('')
const deviceName = ref('')

// 日期格式化
const formatDateTime = (dateString?: string | null): string => {
  return dateString ? dayjs(dateString).format('YYYY-MM-DD HH:mm:ss') : '-'
}

// 查询登记记录
const fetchRecords = async () => {
  if (!circulationId.value) {
    return
  }
  
  try {
    loading.value = true
    const res = await listDeviceRegisterRecords(circulationId.value)
    
    if (res.success && res.data) {
      recordList.value = Array.isArray(res.data) ? res.data : []
    } else {
      recordList.value = []
      Message.error(res.msg || res.message || '获取登记记录失败')
    }
  } catch (error: any) {
    console.error('获取登记记录失败:', error)
    recordList.value = []
    const errorMsg = error?.message || error?.msg || error?.response?.data?.message || '获取登记记录失败，请重试'
    Message.error(errorMsg)
  } finally {
    loading.value = false
  }
}

// 导出Excel
const handleExport = async () => {
  if (!circulationId.value) {
    Message.warning('无法导出：设备ID不存在')
    return
  }
  
  try {
    exportLoading.value = true
    await useDownload(
      () => exportDeviceRegisterRecords(circulationId.value),
      true,
      `${deviceName.value || '设备'}_登记记录_${dayjs().format('YYYY-MM-DD_HH-mm-ss')}`,
      '.xlsx'
    )
    Message.success('导出成功')
  } catch (error: any) {
    console.error('导出失败:', error)
    const errorMsg = error?.message || error?.msg || '导出失败，请重试'
    Message.error(errorMsg)
  } finally {
    exportLoading.value = false
  }
}

// 监听弹窗显示状态
watch(visible, (newVal) => {
  if (newVal) {
    fetchRecords()
  } else {
    // 关闭时清空数据
    recordList.value = []
    circulationId.value = ''
    deviceName.value = ''
  }
})

// 打开弹窗
const open = (id: string, name: string) => {
  circulationId.value = id
  deviceName.value = name || ''
  visible.value = true
}

defineExpose({
  open
})
</script>

<style scoped lang="scss">
.modal-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  padding-right: 30px;
  
  .arco-btn {
    margin-right: 0;
  }
}

:deep(.arco-table) {
  .arco-table-th {
    background-color: var(--color-fill-2);
    font-weight: 500;
  }
}
</style>

